<template>
  <basic-drawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <basic-form @register="registerForm">
      <template #roles>
        <Select :options="options" v-model:value="roles" mode="multiple" />
      </template>
    </basic-form>
  </basic-drawer>
</template>

<script setup lang="ts">
  import { SelectProps, Select } from 'ant-design-vue';
  import { ref, unref } from 'vue';
  import { accountFormSchema } from './account.data';
  import RoleApi from '/@/api/sys/role.class';
  import UserApi from '/@/api/sys/user.class';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicForm, useForm } from '/@/components/Form/index';
  const userApi = new UserApi();
  const emit = defineEmits(['success']);
  const roleApi = new RoleApi();
  const isUpdate = ref(true);
  const options = ref<SelectProps['options']>([]);
  const roles = ref([]);
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    schemas: accountFormSchema,
    showActionButtonGroup: false,
  });
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    isUpdate.value = !!data?.isUpdate;
    if (options.value?.length == 0) {
      const roles = await roleApi.all();
      options.value = roles.map((item) => ({ label: item.label, value: item.id }));
    }
    if (unref(isUpdate)) {
      roles.value = data.record.roleIds;
      setFieldsValue({ ...data.record });
    } else {
      roles.value = [];
    }
  });

  async function handleSubmit() {
    try {
      setDrawerProps({ confirmLoading: true });
      const value = await validate();
      value.roles = roles.value.map((item) => ({ id: item }));
      if (isUpdate.value == true) {
        await userApi.update(value);
      } else {
        await userApi.create(value);
      }
      console.log('ok========');
      emit('success');
      closeDrawer();
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>

<style scoped></style>
